import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login, getUserInfo, logout } from '@/api/auth'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router from '@/router'

export interface UserInfo {
  id: number
  username: string
  nickname: string
  email: string
  avatar: string
  roles: string[]
  permissions: string[]
}

export const useUserStore = defineStore('user', () => {
  const token = ref<string>(getToken() || '')
  const userInfo = ref<UserInfo | null>(null)
  const permissions = ref<string[]>([])

  // 初始化用户信息
  const initUser = () => {
    const savedToken = getToken()
    if (savedToken) {
      token.value = savedToken
    }
  }

  // 登录
  const loginAction = async (loginForm: { username: string; password: string }) => {
    try {
      const response = await login(loginForm)
      const { access_token, user } = response.data
      
      token.value = access_token
      userInfo.value = user
      permissions.value = user.permissions || []
      
      setToken(access_token)
      
      return Promise.resolve()
    } catch (error) {
      return Promise.reject(error)
    }
  }

  // 获取用户信息
  const getUserInfoAction = async () => {
    try {
      const response = await getUserInfo()
      const user = response.data
      
      userInfo.value = user
      permissions.value = user.permissions || []
      
      return user
    } catch (error) {
      return Promise.reject(error)
    }
  }

  // 登出
  const logoutAction = async () => {
    try {
      // await logout()
      console.log('logout')
    } catch (error) {
      console.error('登出请求失败:', error)
    } finally {
      token.value = ''
      userInfo.value = null
      permissions.value = []
      removeToken()
      
      // 跳转到登录页
      router.push('/login')
    }
  }

  // 检查权限
  const hasPermission = (permission: string): boolean => {
    return permissions.value.includes(permission) || permissions.value.includes('*')
  }

  // 检查角色
  const hasRole = (role: string): boolean => {
    return userInfo.value?.roles?.includes(role) || false
  }

  return {
    token,
    userInfo,
    permissions,
    initUser,
    login: loginAction,
    getUserInfo: getUserInfoAction,
    logout: logoutAction,
    hasPermission,
    hasRole
  }
})